import axios from 'axios'

const service = axios.create({
    baseURL: '',
    timeout: 5000
})

service.interceptors.request.use(
    config => {
        if (config.url !== '/user/login') {
            config.headers.Authorization = localStorage.getItem('apptoken')
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)

service.interceptors.response.use(
    ({ data, config }) => {
        var { url } = config
        if (data.code === 200 && url === '/user/login') {
            localStorage.setItem('apptoken', data.data)
        }
        if (data.code === 200 && url === '/user/logout') {
            localStorage.removeItem('apptoken')
        }
        if (data.code === 200) {
            return data
        } else {
            return Promise.reject(new Error(data.msg))
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
